package com.sinosoft.jwjw.component.controller.system;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.sinosoft.jwjw.base.BaseController;
import com.sinosoft.jwjw.component.model.system.SMenu;
import com.sinosoft.jwjw.component.model.system.SUser;
import com.sinosoft.jwjw.component.service.system.RedisService;
import com.sinosoft.jwjw.component.service.system.SMenuService;
import com.sinosoft.jwjw.component.service.system.SUserService;
import com.sinosoft.jwjw.utils.ConvertUtil;
import com.sinosoft.jwjw.utils.CookieUtil;
import com.sinosoft.jwjw.utils.ResultDetail;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author: ericliu
 * @date: 2019/2/18
 * @description:
 */

@Controller
public class LoginController extends BaseController {

    /**
     * 当前系统id
     */
    @Value("${default.systemId}")
    private String DEFAULT_SYSTEM_ID = "";

    @Autowired
    SUserService sUserService;

    @Autowired
    SMenuService sMenuService;

    @Autowired
    RedisService redisService;

    /**
     * 测试是否成功启动
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/")
    public String index() {

        //test redis
        String str1 = redisService.getSUser("aaa");
        redisService.setSUser("aaa","{aa='bbbbbb'}");
        String str2 = redisService.getSUser("aaa");


        String str = SecureUtil.md5("1");


        return "api ok";
    }


    /**
     * 登录统一入口
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login")
    public String login(HttpServletResponse response) {

        //获取参数
        RequestParamUtils();
        ResultDetail result = new ResultDetail();


        String loginName = ConvertUtil.toString(params.get("login"));
        String loginPassword = ConvertUtil.toString(params.get("pw"));//md5以后的
        String systemId = DEFAULT_SYSTEM_ID; //ConvertUtil.toString(params.get("systemId"));
        String isSaveLoginName = ConvertUtil.toString(params.get("isSaveLoginName"));

        if ("".equals(loginName)) {
            result.setCode(501);
            result.setMsg("用户名不能为空");
            return result.toString();
        }
        if ("".equals(loginPassword)) {
            result.setCode(502);
            result.setMsg("密码不能为空");
            return result.toString();
        }
        if ("".equals(systemId)) {
            result.setCode(503);
            result.setMsg("系统id不能为空");
            return result.toString();
        }

        result = loginSystem(loginName , loginPassword , systemId);
        //根据errcode判断各种跳转

        //记录cookie
        if("1".equals(isSaveLoginName) && result.getCode() == 0){
            CookieUtil.addCookie(response , "defaultLoginName" , loginName , 86400*365);
        }
        else{
            CookieUtil.delCookie(response , "defaultLoginName");
        }

        return result.toString();
    }


    public ResultDetail loginSystem(String loginName , String loginPassword, String systemId) {

        //获取参数
        RequestParamUtils();
        ResultDetail result = new ResultDetail();

        //验证用户名密码是否匹配
        result = sUserService.checkLogin(loginName , loginPassword);

        //登录成功
        if(result.getCode() == 0){
            // 1 获取用户角色
            // 2 根据系统id，获取菜单权限（暂不考虑角色切换，所有角色）

            SUser sUser = ConvertUtil.toObject(result.getResult(), SUser.class);
            String userId = sUser.getId();

            List<SMenu> list = sMenuService.selectAuthMenuBySystemIdAndUserId(userId , systemId);
            if (list == null) {
                result.setCode(701);
                result.setMsg("本系统无权限菜单！");
                return result;
            }

            //set redis user
            redisService.setSUser(userId , result.getResult().toString());
            //set redis userSystemMenu
            redisService.setSUserSystemMenu(userId ,systemId , ConvertUtil.toJSONArray(list).toString());


            return result;
        }
        else{
            //登录不成功
            return result;
        }
    }


    /**
     * 登出统一入口
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/logout")
    public String logout() {
        //删除缓存
        //删除cookie
        return "logout ok";
    }
}
